def f(x):
    return x * (x + 2)


def binary_search_min(a, b, epsilon):
    mid = (a + b) / 2
    iter_count = 0
    while (b - a) / 2 > epsilon:
        mid = (a + b) / 2
        if f(mid) > f(a):  # 如果中点左侧的函数值更小，则最小值在左侧
            b = mid
        else:  # 否则，最小值在右侧或就是中点
            a = mid
        iter_count += 1
    return mid, iter_count


# 分别计算不同精度下的结果
epsilon_values = [0.1, 0.01, 0.001]
for epsilon in epsilon_values:
    min_x, iter_count = binary_search_min(-3, 5, epsilon)
    min_y = f(min_x)
    print(f"Epsilon = {epsilon}: Minimum x ≈ {min_x:.4f}, Minimum y ≈ {min_y:.4f} Iterations = {iter_count}")